// miniprogram/pages/player/player.js
let musiclist = []
let nowPlyaingIndex = 0
const backgroundAudioManager = wx.getBackgroundAudioManager()
const app = getApp()
const userLikeCollection = wx.cloud.database().collection('user-like')
let LIKE_SINGS  
let count
Page({

  /**
   * 页面的初始数据
   */
  data: {
    picUrl: '',
    isPlaying: false,
    isLyricShow: false,
    lyric: '',
    isSame: false,
    Like: 'like',
    openid: '',
    musicId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    nowPlyaingIndex = options.index
    musiclist = wx.getStorageSync('musiclist')
    this.loadMusicDetail(options.musicId)
    this.getOpenId()
    this.setData({
      musicId: options.musicId
    })
    this.getLikeSing()
    this.setData({
      Like:'like'
    })
    
  },
  getOpenId () {
    wx.cloud.callFunction({
      name: "login"
    }).then((res) => {
      this.setData({
        openid: res.result.openid
      })
    })
  },
  loadMusicDetail(musicId){
    if(musicId === app.getPlayMusicId()){
      this.setData({
        isSame: true
      })
    } else {
      this.setData({
        isSame: false
      })
      if(!this.data.isSame){
        backgroundAudioManager.stop()
      }
    }
    const music = musiclist[nowPlyaingIndex]
    wx.setNavigationBarTitle({
      title: music.name,
    })
    this.setData({
      picUrl: music.al.picUrl
    })
    app.setPlayMusicId(musicId)
    wx.showLoading({
      title: '歌曲加载中'
    })
    wx.cloud.callFunction({
      name: 'music',
      data: {
        $url: 'musicUrl',
        musicId
      }
    }).then((res) => {
      
      const result = res.result.data[0]
      //判断权限
      if(result.url == null){
        wx.showToast({
          title: '无权限播放',
        })
        return
      }

      //result 返回是单个歌单地址
      //music是歌单具体的信息
      if(!this.data.isSame){
        backgroundAudioManager.src = result.url
        backgroundAudioManager.title = music.name
        backgroundAudioManager.singer = music.ar[0].name
        backgroundAudioManager.epname = music.al.name
        this.savePlayHistory()
      }
      //加载歌词
      wx.cloud.callFunction({
        name: 'music',
        data: {
          musicId,
          $url: 'lyric'
        }
      }).then((res) => {
        let result = ''
        if( res.result && res.result.lrc){
          result = res.result.lrc.lyric
        }
        let  lyric = '暂无歌词'
        if(result){
          lyric = result
        }
        this.setData({
          lyric
        })
      })
      this.setData({
        isPlaying: true
      })
      wx.hideLoading()
    })
  }
  ,
  togglePlaying () {
    if(this.data.isPlaying){
      backgroundAudioManager.pause()
    }else{
      backgroundAudioManager.play()
    }
    this.setData({
      isPlaying: !this.data.isPlaying
    })
  },
  onPrev(){
    nowPlyaingIndex--
    if(nowPlyaingIndex < 0){
      nowPlyaingIndex = musiclist.length - 1
    }
    this.loadMusicDetail(musiclist[nowPlyaingIndex].id)
    this.setData({
      Like:'like'
    })
    this.isLike(musiclist[nowPlyaingIndex].id)
  },
  onNext(){
    nowPlyaingIndex++
    if(nowPlyaingIndex === musiclist.length){
      nowPlyaingIndex = 0
    }
    this.loadMusicDetail(musiclist[nowPlyaingIndex].id)
    this.setData({
      Like:'like'
    })
    this.isLike(musiclist[nowPlyaingIndex].id)
  },
  onChangeLyricShow () {
    this.setData({
      isLyricShow: !this.data.isLyricShow
    })
  },
  timeUpdate (event) {
    this.selectComponent('.lyric').update(event.detail.currentTime)
  },
  onPlay () {
    this.setData({
      isPlaying: true
    })
  },
  onPause () {
    this.setData({
      isPlaying: false
    })
  },
  //播放历史
  savePlayHistory () {
    const music = musiclist[nowPlyaingIndex]
    const openid = app.globalData.openid
    const history = wx.getStorageSync(openid) || []
    let have = false
    for (let i = 0; i < history.length; i++) {
      if(history[i].id == music.id) {
        have = true
        break
      }
    }
    if(!have) {
       history.unshift(music)
       wx.setStorage({
         key: openid,
         data: history
       })  
    }
  },
  toLike () { 
    const music = musiclist[nowPlyaingIndex]
    if(this.data.Like === 'like'){
      this.setData({
        Like: 'like-actived'
      })
      if(count === 0){
        userLikeCollection.add({
          data: {
            like_sings: [music]
          }
        })
      } else {
        LIKE_SINGS.unshift(music)
        userLikeCollection.where({
          _openid: this.data.openid
        }).update({
          data: {
            like_sings: LIKE_SINGS
          }
        })
      }   
    } else {
      this.setData({
        Like:'like'
      })
      const music = musiclist[nowPlyaingIndex]
      LIKE_SINGS = LIKE_SINGS.filter(item=> item.id !== music.id)
      userLikeCollection.where({
        _openid: this.data.openid
      }).update({
        data: {
          like_sings: LIKE_SINGS
        }
      })
      
    }
  },
  getLikeSing() {
    userLikeCollection.where({
      _openid: this.data.openid
    }).count().then(res => {
      count = res.total
    })
    userLikeCollection.where({
      _openid: this.data.openid
    }).get().then((res) => {
      if(res.data.length){
        LIKE_SINGS = res.data[0].like_sings
        this.isLike(this.data.musicId)
      } else{
        LIKE_SINGS = []
      }
    })
  },
  isLike (musicId) {
    LIKE_SINGS.map(item => {
      if(item.id === Number(musicId)){
        this.setData({
          Like: 'like-actived'
        })
      } 
    })
  },
  onComment() {
    const musicId = this.data.musicId
    wx.navigateTo({
      url: `/pages/comment/comment?musicId=${musicId}`,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})